package com.lanchetech.service.impl;


import com.lanchetech.common.enums.FreezeStatusEnum;
import com.lanchetech.common.enums.FreezeTypeEnum;
import com.lanchetech.dao.FreezeAmountMapper;
import com.lanchetech.dao.OrdersMapper;
import com.lanchetech.entity.FreezeAmount;
import com.lanchetech.entity.Orders;
import com.lanchetech.service.FinanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;


@Service
public class FinanceServiceImpl implements FinanceService {

    @Autowired
    FreezeAmountMapper freezeAmountMapper;

    @Autowired
    OrdersMapper ordersMapper;

    @Override
    public void createFreezeAmount(Orders orders, BigDecimal amount, Byte type) {
        // 1、先统计一下当前冻结金额

        BigDecimal freeze = freezeAmountMapper.sumByOrderId(orders.getId());

        if (freeze == null) {
            freeze = BigDecimal.ZERO;
        }

        // 如果为null就不处理
        Byte freezeStatus = null;
        BigDecimal finalAmount = BigDecimal.ZERO;

        if (!FreezeTypeEnum.ORDERS.getType().equals(type) && !FreezeTypeEnum.OTHER_FREEZE.getType().equals(type)) {
            // 解冻

            // 判断是否还有解冻空间
            if (freeze.compareTo(BigDecimal.ZERO) > 0) {

                // 如果是发货解冻，则解冻的金额应该为冻结的50%
                // 如果是确认收货解冻，则按正常流程走

                if (amount.compareTo(freeze) < 0) {
                    finalAmount = amount;
                    freezeStatus = FreezeStatusEnum.PART_FREEZE.getStatus();
                } else {
                    // 如果大于，就取freeze，进行全部解冻
                    finalAmount = freeze;
                    freezeStatus = FreezeStatusEnum.NO_FREEZE.getStatus();
                }

            }
        } else {
            // 冻结
            finalAmount = amount;
            freezeStatus = FreezeStatusEnum.ALL_FREEZE.getStatus();
        }

        if (finalAmount.compareTo(BigDecimal.ZERO) > 0) {
            if (!FreezeTypeEnum.ORDERS.getType().equals(type) && !FreezeTypeEnum.OTHER_FREEZE.getType().equals(type)) {
                finalAmount = finalAmount.negate();
            }
            freezeAmountMapper.insert(FreezeAmount.builder()
                    .orderId(orders.getId())
                    .amount(finalAmount)
                    .type(type)
                    .createdAt(new Date())
                    .tenantId(orders.getTenantId())
                    .build());

            ordersMapper.updateFreezeStatusById(freezeStatus, orders.getId());
        }
    }
}